<?php

class UserIdentity extends CUserIdentity
{
	private $_id;
	
    public function authenticate($verify = false)
    {
        $r = User::model()->find('email =:email AND state =:state',array(':email' => $this->username, ':state' => 1));

        /*$verify - если равно true то залогинит без пароля, используется для авторизации по хешу*/
       	if(!PasswordHelper::verifyPassword($r->pass, $this->password) && !$verify)
		{
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
		}
        else
        {
			$this->setState('email', $r->email);
			$this->setState('phone', $r->phone);
			$this->setState('type', $r->type);
			$this->_id = $r->id;
            $this->errorCode = self::ERROR_NONE;

            switch (intval($r->type)) 
            {
            	case User::TYPE_STAFF_ADMIN:	{ $this->staffAdmin(); }break;
            	case User::TYPE_STAFF_MANAGER:	{ $this->staffManager(); }break;
             	case User::TYPE_SHOP_ADMIN:		{ $this->shopAdmin(); }break;
            	case User::TYPE_SHOP_MANAGER:	{ $this->shopManager(); }break;
             	case User::TYPE_CLIENT:			{ $this->client(); }break;
            	
            	default:{}break;
            }
        }
        return !$this->errorCode;
    }

	public function getId()
    {
        return $this->_id;
    }

    private function staffAdmin()
    {
    	$staff = Staff::model()->find('id_user =:id', array(':id' => $this->_id));
    	$this->setState('name', $staff->name);
    	$this->setState('url', Yii::app()->urlManager->baseUrl.'/staff/');
    }
    
    private function staffManager()
    {
    	$staff = Staff::model()->find('id_user =:id', array(':id' => $this->_id));
    	$this->setState('name', $staff->name);
    	$this->setState('url', Yii::app()->urlManager->baseUrl.'/staff/');
    }
    
    private function shopAdmin()
    {
    	$shop = Shop::model()->find('id_user =:id', array(':id' => $this->_id));
    	$this->setState('name', $shop->name);
    	$this->setState('site_link', $shop->site_link);
    	$this->setState('address', $shop->address);
    	$this->setState('url', Yii::app()->urlManager->baseUrl.'/shop/');
    }
    
    private function shopManager()
    {
    	$shop = Shop::model()->find('id_user =:id', array(':id' => $this->_id));
    	$this->setState('name', $shop->name);
    	$this->setState('site_link', $shop->site_link);
    	$this->setState('address', $shop->address);
    	$this->setState('url', Yii::app()->urlManager->baseUrl.'/shop/');
    }

    private function client()
    {
    	$client = Client::model()->find('id_user =:id', array(':id' => $this->_id));
    	$this->setState('name', $client->name);
        $this->setState('url', Yii::app()->urlManager->baseUrl.'/client/');
    }
}